package com.epfresh.adapter;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.text.TextPaint;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.baidu.platform.comapi.map.D;
import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.FitCenter;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions;
import com.bumptech.glide.request.RequestOptions;
import com.epfresh.R;
import com.epfresh.api.universalimageloader.core.DisplayImageOptions;
import com.epfresh.api.universalimageloader.core.ImageLoader;
import com.epfresh.api.universalimageloader.core.assist.ImageScaleType;
import com.epfresh.api.utils.LocalDisplay;
import com.epfresh.bean.HomeTopEntityNew;
import com.epfresh.bean.NewHomeBean;
import com.epfresh.global.BaseApplication;
import com.makeramen.roundedimageview.RoundedImageView;

import multitype.ItemViewBinder;

/**
 * Author: Chen
 * Date: 2019/1/18
 * Desc:
 */
public class MarketViewBinderNew extends ItemViewBinder<NewHomeBean.MarketsBean, MarketViewBinderNew.ViewHolder> {
    private Context context;
    private OnMarketClickListener onMarketClickListener;

    public void setOnMarketClickListener(OnMarketClickListener onMarketClickListener) {
        this.onMarketClickListener = onMarketClickListener;
    }

    public MarketViewBinderNew(Context context) {
        this.context = context;
    }

    @NonNull
    @Override
    protected ViewHolder onCreateViewHolder(@NonNull LayoutInflater inflater, @NonNull ViewGroup parent) {
        View itemView = inflater.inflate(R.layout.layout_market, parent, false);
        return new ViewHolder(itemView);
    }

    @Override
    protected void onBindViewHolder(@NonNull final ViewHolder holder, @NonNull final NewHomeBean.MarketsBean item) {
//        if (item.isChangBg()) {
//            holder.img_bg.setVisibility(View.VISIBLE);
//            ImageLoader.getInstance().displayImage(item.getBgUrl(), holder.img_bg, optionsBanner);
//        } else {
//            holder.img_bg.setVisibility(View.GONE);
//        }
        if (item.getMarketing() != null && item.getMarketing().getImg() != null) {
            holder.img_ad.setVisibility(View.VISIBLE);
            Glide.with(context).load(item.getMarketing().getImg())
//                .apply(RequestOptions.errorOf(R.drawable.pic_load_error))
                    .apply(RequestOptions.priorityOf(Priority.HIGH))
                    .apply(RequestOptions.diskCacheStrategyOf(DiskCacheStrategy.AUTOMATIC))
                    .apply(new RequestOptions().transforms(new CenterCrop(),new RoundedCorners(LocalDisplay.dp2px(10))))
                    .transition(DrawableTransitionOptions.withCrossFade())
                    .into(holder.img_ad);
        } else {
            holder.img_ad.setVisibility(View.GONE);
        }

        ImageLoader.getInstance().displayImage(item.getLogo(), holder.img_market, options);
        holder.txt_market_name.setText(item.getShortName());

        holder.txt_merchant.setText("商户  " + item.getStoreCount() + "家");
        holder.txt_goods.setText("商品  " + item.getProductCount() + "个");

        adaptiveDisplayCategory(holder, item);


        holder.vf_tips.removeAllViews();
        for (String s : item.getDynamic()) {
            View view = View.inflate(context, R.layout.item_vf, null);
            TextView tip = view.findViewById(R.id.txt);
            tip.setSingleLine();
            tip.setText(s);
            holder.vf_tips.addView(view);
        }

        if (item.getDynamic().size() == 1) {
            holder.vf_tips.stopFlipping();
        } else {
            holder.vf_tips.startFlipping();
        }

        holder.ll_market.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (onMarketClickListener != null) {
                    onMarketClickListener.toMarket(item);
                }
            }
        });
        holder.img_ad.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (onMarketClickListener != null) {
                    onMarketClickListener.onAdClick(item);
                }
            }
        });
    }


    private void adaptiveDisplayCategory(ViewHolder holder, NewHomeBean.MarketsBean item) {
        if (item.getCategoryCnt() != null && item.getCategoryCnt().size() > 0) {

            String realStr = generateRealStr(item);
            holder.txt_category.setText(realStr);
        }
    }

    private String generateRealStr(NewHomeBean.MarketsBean item) {
        String saveStr = null;
        StringBuilder sb = new StringBuilder();
        int size;

        if (item.getCategoryCnt().size() >= 4) {
            size = 4;
        } else {
            size = item.getCategoryCnt().size();
        }

        for (int i = 0; i < size; i++) {
            if (i == 0) {
                sb.append(item.getCategoryCnt().get(i).getName()).append("  ").append(item.getCategoryCnt().get(i).getProductCount());
            } else {
                sb.append("    ").append(item.getCategoryCnt().get(i).getName()).append("  ").append(item.getCategoryCnt().get(i).getProductCount());
            }

            if (!checkIsCanShow(sb.toString())) {
                return saveStr;
            }
            saveStr = sb.toString();
        }
        return saveStr;
    }

    private boolean checkIsCanShow(String s) {
        int showWidth = getScreenWidth(context) - LocalDisplay.dp2px(126);
        float textWidth = getTextWidth(s, sp2px(12));
        return textWidth <= showWidth;
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        private ImageView img_market,img_ad, img_bg;
        private TextView txt_market_name, txt_merchant, txt_goods;
        private View ll_market;

        private TextView txt_category;
        private ViewFlipper vf_tips;

        ViewHolder(View itemView) {
            super(itemView);

            img_market = itemView.findViewById(R.id.img_market);
            img_ad = itemView.findViewById(R.id.img_ad);
//            img_bg = itemView.findViewById(R.id.img_bg);
            txt_market_name = itemView.findViewById(R.id.txt_market_name);
            txt_merchant = itemView.findViewById(R.id.txt_merchant);
            txt_goods = itemView.findViewById(R.id.txt_goods);
            ll_market = itemView.findViewById(R.id.ll_market);

            txt_category = itemView.findViewById(R.id.txt_category);

            vf_tips = itemView.findViewById(R.id.vf_tips);
        }
    }

    /**
     * 获取文本的显示宽度
     *
     * @param text
     * @param textSize
     * @return
     */
    public float getTextWidth(String text, float textSize) {

        TextPaint textPaint = new TextPaint();
        textPaint.setTextSize(textSize);
        return textPaint.measureText(text);
    }

    /**
     * SP转换PX,保证文字大小不变
     *
     * @param spValue
     * @return
     */
    public int sp2px(float spValue) {
        final float fontScale = BaseApplication.getInstance().getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }

    /**
     * 获得屏幕的宽
     *
     * @param context
     * @return
     */
    public int getScreenWidth(Context context) {
        WindowManager wm = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        if (wm != null) {
            wm.getDefaultDisplay().getMetrics(outMetrics);
            return outMetrics.widthPixels;
        }
        return 0;
    }

    private DisplayImageOptions options = new DisplayImageOptions.Builder()
            .showImageOnLoading(R.mipmap.icon_fail_merchant) //设置图片在下载期间显示的图片
            .showImageForEmptyUri(R.mipmap.icon_fail_merchant)//设置图片Uri为空或是错误的时候显示的图片
            .showImageOnFail(R.mipmap.icon_fail_merchant)
            .cacheInMemory(true)// 设置下载的图片是否缓存在内存中
            .cacheOnDisk(true)// 设置下载的图片是否缓存在SD卡中
            .considerExifParams(true) // 是否考虑JPEG图像EXIF参数（旋转，翻转）
            .imageScaleType(ImageScaleType.EXACTLY_STRETCHED)// 设置图片以如何的编码方式显示
            .bitmapConfig(Bitmap.Config.RGB_565)
            .build();

    public interface OnMarketClickListener {
        void toMarket(NewHomeBean.MarketsBean item);

        void onAdClick(NewHomeBean.MarketsBean item);
    }

}
